<?php

namespace app\common\model;

use think\Db;
use think\Model;
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'add_time';
    protected $updateTime = 'edit_time';
    // 追加属性
    protected $append = ['image','industry_name','company_type','position_name'];

    /**
     * 获取用户信息
     * @param int $user_id 用户id
     */
    public static function user_info(int $user_id)
    {
        $where = "user_id = {$user_id}";
        $info = self::where($where)->field("*")->find()->toArray();
        $where = "user_id = {$user_id}";
        $user_circle_number = Db::name("user_circle")->where($where)->count();
        $c_where = "c.user_id = {$user_id}";
        $c_where.= " AND uc.isshow = '1'";
        $c_where.= " AND uc.isshow_pt = '1'";
        $user_collect_number = Db::name("collect")->alias("c")->join("user_circle uc","uc.id = c.circle_id")->where($c_where)->count();
        $info["user_circle_number"] = $user_circle_number;
        $info["user_collect_number"] = $user_collect_number;
        $price = Db::name("chat_group_user")->where(["user_id"=>$user_id,"ispay"=>1,"is_tui"=>0])->sum("price");
        $info['price'] = $price;
        $info['tel'] = hide_phone($info['tel']);
        $cleaned_data = array_map(function ($value) {
            return ($value === null) ? "" : $value;
        }, $info);
        return $cleaned_data;
    }

    public static function getUserList($params,$user_id,$group_type)
    {
        if(isset($params['search'])){
            $search = $params['search'];
        }else{
            $search = "";
        }
        if(!isset($params['page']) && empty($params['page'])){
            $page = 1;
        }else{
            $page = $params['page'];
        }
        $where = "is_jin = '0'";
        $where.= " AND logout = '0'";
        $where.= " AND user_id != {$user_id}";
        if($group_type == 2){
            $where.= " AND authen = '3'";
        }
        if(isset($params["industry_id"]) && !empty($params["industry_id"])){
            $where.= " AND industry_id = {$params['industry_id']}";
        }
        if(isset($params["is_phone"]) && $params["is_phone"] == 1){
            if($search){
                $where.= " AND tel like '%$search%'";
            }
        }
        if(isset($params["is_remark"]) && !empty($params["is_remark"])){
            if($search){
                $where.= " AND remark like '%$search%'";
            }
        }
        if(isset($params["username"]) && !empty($params["username"])){
            $username = $params["username"];
            if($username){
                $where.= " AND username like '%$username%'";
            }
        }
        $count = self::where($where)->field("user_id,username,image,industry_id,company_typeid,position_id")->count();
        $limit = 20;
        $start = ($page - 1) * $limit;
        $total = ceil($count / $limit);
        $list = self::where($where)->field("user_id,username,image,industry_id,company_typeid,position_id")->limit($start, $limit)->select();
        $data = [
            'total'=>$total,
            'list'=>$list
        ];
        return $data;
    }

    public static function getGroupMembers($page,$search,$user_ids,$jin_userids)
    {
        $where = "is_jin = '0'";
        $where.= " AND logout = '0'";
        $where.=" AND user_id IN ($user_ids)";
        if(isset($search) && !empty($search)){
            //$where.= " AND username like '%$search%'";
            $where.=" AND (remark LIKE '%".$search."%'";
            $where.=" OR tel LIKE '%".$search."%')";
        }
        $count = self::where($where)->field("username,image,industry_id,company_typeid,position_id")->count();
        $limit = 20;
        $start = ($page - 1) * $limit;
        $total = ceil($count / $limit);
        $list = self::where($where)->field("user_id,username,image,industry_id,company_typeid,position_id")->limit($start, $limit)->select();
        if($jin_userids){
            $in_user_arr = explode(",",$jin_userids);
        }else{
            $in_user_arr = [];
        }
        foreach ($list as $value){
            if (in_array($value['user_id'],$in_user_arr)){
                $value["is_jin"] = 1;
            }else {
                $value["is_jin"] = 0;
            }
        }
        $data = [
            'total'=>$total,
            'list'=>$list
        ];
        return $data;
    }

    public static function inviteGroupMembers($page,$search,$user_ids,$group_type)
    {
        $user_id_arr = explode(",",$user_ids);
        $where = "is_jin = '0'";
        $where.= " AND logout = '0'";
        if($group_type == 2){
            $where.= " AND authen = '3'";
        }
        if(isset($search) && !empty($search)){
            //$where.= " AND username like '%$search%'";
            $where.=" AND (remark LIKE '%".$search."%'";
            $where.=" OR tel LIKE '%".$search."%')";
        }
        $count = self::where($where)->field("user_id,username,image,industry_id,company_typeid,position_id")->count();
        $limit = 20;
        $start = ($page - 1) * $limit;
        $total = ceil($count / $limit);
        $list = self::where($where)->field("user_id,username,image,industry_id,company_typeid,position_id")->limit($start, $limit)->select();
        foreach ($list as &$value){
            if (in_array($value['user_id'],$user_id_arr)){
                $value["is_existence"] = 1;
            }else {
                $value["is_existence"] = 0;
            }
        }
        $data = [
            'total'=>$total,
            'list'=>$list
        ];
        return $data;
    }

    /**
     * 登录方法
     * @param string $union_id
     * @param string $openid
     * @param string $head_img
     * @param string $nickname
     */
    public static function login($union_id,$openid)
    {
        $where = "unionid = '{$union_id}' AND (logout = '0' OR logout = '3')";
        $info = self::where($where)->order("user_id","desc")->find();
        if (empty($info)){
            $time = time();
            $insert = [
                'username'=>randomNumber(),
                'tel'=>'',
                'is_jin'=>0,
                'image'=>'/uploads/th.png',
                'unionid'=>$union_id,
                'open_id'=>$openid,
                'add_time'=>$time,
                'edit_time'=>$time,
            ];
            return self::create($insert);
        }else{
            if(empty($info['open_id'])){
                self::where($where)->update(["open_id"=>$openid]);
            }
            $info = self::where($where)->order("user_id","desc")->find();
            return $info;
        }
    }

    public static function appLogin($union_id,$app_open_id)
    {
        $where = "unionid = '{$union_id}' AND (logout = '0' OR logout = '3')";
        $info = self::where($where)->order("user_id","desc")->find();
        if (empty($info)){
            $time = time();
            $insert = [
                'username'=>randomNumber(),
                'tel'=>'',
                'is_jin'=>0,
                'image'=>'/uploads/th.png',
                'unionid'=>$union_id,
                'app_open_id'=>$app_open_id,
                'add_time'=>$time,
                'edit_time'=>$time,
            ];
            return self::create($insert);
        }else{
            if(empty($info['app_open_id'])){
                self::where($where)->update(["app_open_id"=>$app_open_id]);
            }
            $info = self::where($where)->order("user_id","desc")->find();
            return $info;
        }
    }

    /**
     * 获取个人头像
     */
    public function getImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    public function getIndustryNameAttr($value,$data)
    {
        if($data['industry_id']){
            $industry_name = Db::name("industry")->where("id",$data["industry_id"])->value("name");
            return $industry_name;
        }else{
            return "";
        }
    }

    public function getCompanyTypeAttr($value,$data)
    {
        if($data['company_typeid']){
            $company_type = Db::name("company_type")->where("id",$data["company_typeid"])->value("name");
            return $company_type;
        }else{
            return "";
        }
    }

    public function getPositionNameAttr($value,$data)
    {
        if($data['position_id']){
            $position_name = Db::name("position")->where("id",$data["position_id"])->value("name");
            return $position_name;
        }else{
            return "";
        }
    }

    public function getAddAuthenTimeAttr($value)
    {
        if($value){
            return date("Y-m-d",$value);
        }else{
            return "";
        }
    }

    public function getAuthenTimeAttr($value)
    {
        if($value){
            return date("Y-m-d",$value);
        }else{
            return "";
        }
    }

    public function getEndTimeAttr($value)
    {
        if($value){
            return date("Y-m-d",$value);
        }else{
            return "";
        }
    }
    public function getCompanyImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    public function getIdCard1ImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    public function getIdCard2ImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    public function getHandCardImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    public function getWxImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    public function getBackgroundImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return splicing_domain("/uploads/bg.png");
        }
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        //return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                UserCircle::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                Report::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

}
